package com.lechuang.youleduo1.view.activity.home;

import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.support.v7.util.DiffUtil;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.bumptech.glide.Glide;
import com.bumptech.glide.MemoryCategory;
import com.lechuang.youleduo1.R;
import com.lechuang.youleduo1.base.Constants;
import com.lechuang.youleduo1.model.LeCommon;
import com.lechuang.youleduo1.model.bean.GetBean;
import com.lechuang.youleduo1.model.bean.HomeSearchResultBean;
import com.lechuang.youleduo1.presenter.CommonAdapter;
import com.lechuang.youleduo1.presenter.ToastManager;
import com.lechuang.youleduo1.presenter.net.Netword;
import com.lechuang.youleduo1.presenter.net.ResultBack;
import com.lechuang.youleduo1.presenter.net.netApi.HomeApi;
import com.lechuang.youleduo1.utils.Utils;
import com.lechuang.youleduo1.view.defineView.ViewHolder;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Author: guoning
 * Date: 2017/10/2
 * Description:
 */

public class CommFragmentImpl extends CommFragment {


    private Subscription subscribe;
    private int page = 1;

    public CommFragmentImpl() {
        super();
    }


    private CommonAdapter<HomeSearchResultBean.ProductListBean> mAdapter;
    private List<HomeSearchResultBean.ProductListBean> productList = new ArrayList<>();
    private int headImg;

    private void getInfoList() {
        showWaitDialog("");
        HashMap<String, String> map = new HashMap<>();
        map.put("page", page + "");
        if (rootId != -1) {  //Integer classTypeId   分类id,精选不传
            map.put("classTypeId", rootId + "");
        } else {             //Integer is_official   精选传1,其他不传
            map.put("type", 1 + "");
        }

        subscribe = Netword.getInstance().getApi(HomeApi.class)
                .searchResult(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new ResultBack<HomeSearchResultBean>(getActivity()) {
                    @Override
                    public void successed(HomeSearchResultBean result) {
                        hideWaitDialog();
                        if (result == null) return;
                        if (page == 1 && productList != null) {
                            productList.clear();
                        }
                        List<HomeSearchResultBean.ProductListBean> list = result.productList;
                        productList.addAll(list);
                        if (page > 1 && list.isEmpty()) {
                            Utils.show(getActivity(), "亲,已经到底了~");
                            return;
                        }
                        if (page == 1) {
                            mAdapter = new CommonAdapter<HomeSearchResultBean.ProductListBean>(getActivity(), productList, R.layout.item_program_product) {
                                @Override
                                public void setData(ViewHolder viewHolder, Object item) {
                                    HomeSearchResultBean.ProductListBean bean = (HomeSearchResultBean.ProductListBean) item;
                                    //商品图
                                    Glide.with(context).load(bean.imgs).into((ImageView) viewHolder.getView(R.id.iv_img));
                                    //动态调整滑动时的内存占用
                                    Glide.get(context).setMemoryCategory(MemoryCategory.LOW);
                                    viewHolder.setText(R.id.tv_oldprice, "原价 ¥" + bean.price);
                                    viewHolder.setText(R.id.tv_name, bean.name);
                                    viewHolder.setText(R.id.tv_nowprice, "券后价 ¥" + bean.preferentialPrice);
                                    if (bean.shopType != null && bean.shopType.equals("2")) {
                                        headImg = R.drawable.zhuan_tianmao;
                                    } else {  //shopType 1淘宝 2天猫 默认淘宝
                                        headImg = R.drawable.zhuan_taobao;
                                    }
                                    Drawable drawable = context.getResources().getDrawable(headImg);
                                    drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                                    ((TextView) viewHolder.getView(R.id.tv_name)).setCompoundDrawables(drawable, null, null, null);
                                }
                            };
                            mgv.setAdapter(mAdapter);

                        } else {
                            mAdapter.notifyDataSetChanged();
                        }
                        mgv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                            @Override
                            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                                startActivity(new Intent(getActivity(), ProductDetailsActivity.class).
                                        putExtra(Constants.listInfo, JSON.toJSONString(productList.get(position))));
                            }
                        });

                        /*if (page > 1 && list.isEmpty()) {            //数据没有了
                            mRefreshLayout.loadNothing();
                            return;
                        }*/
                      /*  if (page == 1) {
                            if (!mFirstLoadData) {
                                DiffUtil.DiffResult diffResult = DiffUtil.calculateDiff(new DiffUtil.Callback() {
                                    @Override
                                    public int getOldListSize() {
                                        return productList.size();
                                    }

                                    @Override
                                    public int getNewListSize() {
                                        return list.size();
                                    }

                                    @Override
                                    public boolean areItemsTheSame(int oldItemPosition, int newItemPosition) {
                                        return productList.get(oldItemPosition).id.equals(list.get(newItemPosition).id);
                                    }

                                    @Override
                                    public boolean areContentsTheSame(int oldItemPosition, int newItemPosition) {
                                        return productList.get(oldItemPosition).id.equals(list.get(newItemPosition).id);
                                    }
                                });
                                diffResult.dispatchUpdatesTo(infoAdapter);
                            } else {
                                infoAdapter.addData(0, list);
                                mFirstLoadData = false;
                            }
                            //mRefreshLayout.refreshComplete();
                        } else {
                            infoAdapter.addData((page - 1) * PAGE_COUNT, list);
                            //mRefreshLayout.loadMoreComplete();
                        }*/
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        hideWaitDialog();
                    }
                });
    }


    //
    @Override
    protected void onFragmentInvisible() {
        mFirstLoadData = true;

        if (subscribe != null && !subscribe.isUnsubscribed())
            subscribe.unsubscribe();
    }

    @Override
    protected int getLayout() {
        return R.layout.fragment_comment;
    }

    @Override
    protected void onFragmentVisible() {
        rootId = getArguments().getInt(LeCommon.KEY_ROOT_ID);
        if (productList != null)
            productList.clear();
        page = 1;
        //获取数据
        getInfoList();
    }

    //上拉刷新数据
    public void notifyChildPagerLoadData(int newPage) {
        rootId = getArguments().getInt(LeCommon.KEY_ROOT_ID);
        page = newPage;
        getInfoList();
    }
    //下拉加载数据
    public void onPullDownToRefreshData(int newPage) {
        rootId = getArguments().getInt(LeCommon.KEY_ROOT_ID);
        page = newPage;
        getInfoList();
    }

    @Override
    public void show(GetBean.ListInfo listInfo, int position) {

    }

    @Override
    public void tryAgain() {
        // do nothing...
    }
}

